/**
 * AI Advisor - fast local analysis for hospital status and plans
 * Uses local realDataService for instant insights; optionally hits /v1/optimize for plans.
 */

'use client'

import { realDataService } from './realData'
import { API_BASE_URL } from './config'

export interface AdvisorInput {
  // Optional override realtime snapshot. If omitted, computed on the fly.
  snapshot?: ReturnType<typeof realDataService.getAllRealTimeData>
}

export interface AdvisorInsight {
  kpis: Array<{ key: string; value: number; target?: number; status?: string; trend?: number }>
  bottlenecks: string[]
  quickActions: string[]
}

export interface AdvisorPlanResult {
  plans: Array<{ id: string; kpis: Record<string, number> }>
  recommend: string
}

function rankKpiStatus(kpi: { value: number; target?: number; status?: string; trend?: number }): string {
  if (kpi.status) return kpi.status
  if (typeof kpi.target === 'number') {
    const delta = (kpi.value - kpi.target)
    if (Math.abs(delta) <= 0.05 * (kpi.target || 1)) return 'good'
    return delta > 0 ? 'warning' : 'excellent'
  }
  return 'normal'
}

export function analyzeFast(input?: AdvisorInput): AdvisorInsight {
  const snapshot = input?.snapshot ?? realDataService.getAllRealTimeData()

  const kpiEntries = Object.entries(snapshot.kpis).map(([key, v]: any) => ({
    key,
    value: v.value,
    target: v.target,
    status: v.status,
    trend: v.trend
  }))

  // Detect bottlenecks heuristically
  const bottlenecks: string[] = []
  const departmentsBusy = snapshot.departments.filter((d: any) => d.utilizationRate >= 90 || d.waitingTime >= 60)
  if (departmentsBusy.length) bottlenecks.push(`高负载科室: ${departmentsBusy.slice(0, 3).map((d: any) => `${d.name}(${d.utilizationRate}%)`).join('、')}`)

  const maintOrBusyEquip = snapshot.equipment.filter((e: any) => e.status === 'maintenance' || e.status === 'busy')
  if (maintOrBusyEquip.length) bottlenecks.push(`关键设备紧张/维护: ${maintOrBusyEquip.slice(0, 3).map((e: any) => `${e.name}:${e.status}`).join('、')}`)

  const crowdAlerts = snapshot.alerts.filter((a: any) => a.type === 'crowding' || a.severity === 'high')
  if (crowdAlerts.length) bottlenecks.push(`拥挤风险: ${crowdAlerts[0].title}`)

  // Quick actions suggestions
  const quickActions: string[] = []
  if (departmentsBusy.length) quickActions.push('调配医生/护士支援至高负载科室，临时开放机动诊室')
  if (maintOrBusyEquip.length) quickActions.push('将在修/繁忙设备的检查分流至空闲设备，通知设备科加急处理')
  if (crowdAlerts.length) quickActions.push('优化患者流线与分诊，增派志愿者引导，开放备用等候区')

  // Re-rank KPIs with status
  const kpis = kpiEntries.map(k => ({ ...k, status: rankKpiStatus(k) }))

  return { kpis, bottlenecks, quickActions }
}

export async function fetchOptimizePlans(signal?: AbortSignal): Promise<AdvisorPlanResult | null> {
  try {
    const resp = await fetch(`${API_BASE_URL}/optimize/layout`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({}),
      signal
    })
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
    const data = await resp.json()
    return data as AdvisorPlanResult
  } catch (_) {
    return null
  }
}

export interface AdvisorAllResult extends AdvisorInsight {
  plans?: AdvisorPlanResult | null
}

export async function adviseFast(options?: AdvisorInput, signal?: AbortSignal): Promise<AdvisorAllResult> {
  const insight = analyzeFast(options)
  // Fire and forget plan fetch for responsiveness; await with short timeout from caller if needed
  const plans = await fetchOptimizePlans(signal)
  return { ...insight, plans }
}

export default {
  analyzeFast,
  fetchOptimizePlans,
  adviseFast
}

